package com.aso.common.encrypt;

import android.content.Context;


import com.itsdf07.alog.ALog;

import java.security.interfaces.RSAPublicKey;

/**
 * Created by itsdf07 on 2017/8/26.
 */

public class EncryptUtils {
    private static EncryptUtils instance;
    private RSAPublicKey mRsaPublicKey;

    public static EncryptUtils getInstance() {
        if (instance == null) {
            instance = new EncryptUtils();
        }
        return instance;
    }

    public void init(Context context) {
        try {
            mRsaPublicKey = RSA.loadPublicKey(context.getAssets().open("rsa_public_key.pem"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * AES + RSA混合加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public String[] blendEncrypt(String content) throws Exception {
        String[] result = new String[2];
        //生成一个AES密钥
        String aesKey = AES.generateKeyString();
        ALog.i("AES-KEY:%s", aesKey);
        //用RSA公钥加密AES的密钥
        String encryptAesKey = RSA.encryptByPublicKey(aesKey, mRsaPublicKey);
        result[0] = encryptAesKey;
        ALog.i("Encrypt AES-KEY:%s", encryptAesKey);

        //Json内容加密
        String encryptContent = AES.encrypt(content, aesKey);
        result[1] = encryptContent;
        return result;
    }

    /**
     * AES加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public String[] aesEncrypt(String content) throws Exception {
        String[] result = new String[2];
        //生成一个AES密钥
        String aesKey = AES.generateKeyString();
        result[0] = aesKey;
        ALog.i("Encrypt AES-KEY:%s", result[0]);

        //Json内容加密
        String encryptContent = AES.encrypt(content, aesKey);
        result[1] = encryptContent;
        return result;
    }

    public String decryptByRSAPublicKey(String decryptContent) throws Exception {
        return RSA.decryptByPublicKey(decryptContent, mRsaPublicKey);
    }

    public String decryptByAESKey(String decryptContent) throws Exception {
        return AES.decrypt(decryptContent, AES.generateKeyString());
    }
}
